package com.cxliu.cnews.Images.Api;

import com.cxliu.cnews.Images.Bean.ImageBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


/**
 * Created by lcx on 2016/7/11.
 */

public class ApiManager {
    public static ApiService apiManager;

    public static ApiService getApi() {
        if (apiManager == null) {
            intAPI();
        }
        return apiManager;
    }

    public static void intAPI() {
        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl("http://c.m.163.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
        apiManager = mRetrofit.create(ApiService.class);
    }

    public interface ApiService {
        @Headers("User-Agent:Mozilla/5.0")
        @GET("http://api.laifudao.com/open/tupian.json")
        Observable<ResponseBody> getImagesList();
    }

    /**
     * 获取图片信息列表接口
     * @param callback
     */
    public static void getImagesList(final ImagesApiInterface callback) {
        getApi().getImagesList().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).unsubscribeOn(Schedulers.io())
                .subscribe(new Action1<ResponseBody>() {
                    @Override
                    public void call(ResponseBody responseBody) {
                        if (responseBody == null) {
                            callback.onFail();
                            return;
                        }
                        try {
                            String jsonObjectString = responseBody.string();
                            List<ImageBean> items=(new Gson()).fromJson(jsonObjectString,new TypeToken<List<ImageBean>>() {
                            }.getType());
                            callback.onSuccess(items);
                        } catch (IOException e) {
                            e.printStackTrace();
                            callback.onFail();
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        callback.onFail();
                    }
                });
    }

    public interface ImagesApiInterface {

        public void onSuccess(List<ImageBean> beans);

        public void onFail();
    }
}
